package core;

import fileoperation.FileCreation;
import fileoperation.FileDeletion;
import jitobject.Blob;
import jitobject.JitObject;
import jitobject.Tree;
import repository.Repository;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.List;

public class JitCatFile {
    /**
     * cat jit-object
     * if args is '-p', show the content of object
     * else if the args is '-t', show the type of object
     */

    public static void catFile(String dirName, String[] args) throws Exception
    {
        String catType = args[0];
        String hashValue = args[1];
        String dirname = hashValue.substring(0, 2);
        String dirPath = dirName + File.separator + dirname;
        File hashDir = new File(dirPath);
        if(!hashDir.exists() || !hashDir.isDirectory())
        {
            System.out.println("fatal: Not a valid object name " + hashValue);
        }
        String objectName = hashValue.substring(2);
        int nameLength = objectName.length();
        File[] fls = hashDir.listFiles();
        JitObject hashObject = null;
        boolean flag = false;
        for( File fl : fls)
        {
            String flName = fl.getName().substring(0, nameLength);
            if( objectName.equals(flName))
            {
                flag = true;
                hashObject = JitObject.deserialize(fl);
                break;
            }
        }

        if( args[0].equals("-t")) System.out.println(hashObject.getFmt());
        else if(args[0].equals("-p")) System.out.println(hashObject.getValue());

        if( !flag )
            System.out.println("fatal: Not a valid object name " + hashValue);
    }
}
